# -*- coding: utf-8 -*-
"""
Created on Mon Oct  8 14:32:52 2018

@author: luolei

互信息熵
"""

import matplotlib.pyplot as plt
import pandas as pd
import json
import numpy as np
import sys

sys.path.append('../')

from lib import *
from lib.data_analysis import *


if __name__ == '__main__':
	#%% 载入数据
	data = pd.read_csv('../../data/runtime/data_nmlzd.csv')
	data = data.loc[: 20000, :]
	
	#%% 互信息熵计算
	# 参数设定
	bins = [100, 100]		# **手动设置划分网格数，相当于在x和y上的分辨率
	max_lag = 1000  	# **手动设置最大正负检测时滞长度
	lag_step = 1        # **手动设置检测lag步长

	# 进行检测
	plt.figure(figsize = [8, 8 * len(target_cols)])
	total_time_delay_ie = {}
	for col_x in selected_cols:
		total_time_delay_ie[col_x] = {}
		for col_y in target_cols:
			print('processing col_x: {}, col_y: {}'.format(col_x, col_y))

			# 计算total_time_delay_ie结果
			time_delay_ie = time_delay_ie_test(data, col_x, col_y, bins, max_lag, lag_step)
			total_time_delay_ie[col_x][col_y] = time_delay_ie

			# 计算背景均值和标准差
			bg_values = [abs(v) for k, v in time_delay_ie.items() if abs(k) > ie_bg_split_loc]  # ** 注意取了绝对值
			mean, std = np.mean(bg_values), np.std(bg_values)
			sig_thres = mean + 3 * std

			# 画图
			abs_ie_values = np.abs(list(time_delay_ie.values()))

			plt.subplot(
				len(selected_cols), len(target_cols), len(target_cols) * selected_cols.index(col_x) + target_cols.index(col_y) + 1)
			plt.plot(time_delay_ie.keys(), abs_ie_values)
			plt.fill_between(time_delay_ie.keys(), abs_ie_values)
			plt.plot([-max_lag, max_lag], [0, 0], 'k--', linewidth = 0.3)
			plt.plot([-max_lag, max_lag], [sig_thres, sig_thres], 'r', linewidth = 0.5)
			plt.xlim([-max_lag, max_lag])

			max_ie = max(abs_ie_values)
			ylim = None
			if max_ie >= 1.0:
				ylim = [0.0, max_ie // 1 + 1]
			elif 0.5 <= max_ie < 1.0:
				ylim = [0.0, 1.0]
			elif 0.2 <= max_ie < 0.5:
				ylim = [0.0, 0.5]
			elif 0.0 <= max_ie < 0.2:
				ylim = [0.0, 0.2]
			plt.ylim(ylim)
			plt.plot([0, 0], ylim, 'k', linewidth = 0.8)

			plt.xticks(fontsize = 4)
			plt.yticks(fontsize = 4)
			if col_x == selected_cols[0]:
				plt.title(col_y, fontsize = 5)
			plt.legend([col_x], loc = 'lower right', fontsize = 5)

			plt.tight_layout()
			plt.show()
			plt.pause(1.0)

	# %% 保存计算结果
	plt.savefig('../../graph/ie_analysis_fig.png', dpi = 600)
	with open('../../data/runtime/ie_time_delay_correlation_results.json', 'w') as f:
		json.dump(total_time_delay_ie, f)


